package com.huika.renrench.control.common.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import android.annotation.SuppressLint;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huika.lib.utils.VerifyTool;
import com.huika.renrench.R;
import com.huika.renrench.control.common.adapter.ContactAdapter;
import com.huika.renrench.control.common.adapter.ContactAdapter.InviteOnclik;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.support.bean.ContactBean;
import com.huika.renrench.utils.CharacterParser;
import com.huika.renrench.utils.PhoneUtil;
import com.huika.renrench.utils.WebNetUtils;
import com.huika.renrench.view.ClearableEditText;
import com.huika.renrench.view.ContactSideBar;
import com.huika.renrench.view.ContactSideBar.OnTouchingLetterChangedListener;
import com.huika.renrench.view.TitleBarHelper;

/**
 * @description：
 * @author shicm
 * @date 2014年7月3日 上午11:35:54
 *       联系人的识别
 */
public class MobileContactActivity extends BaseAct implements InviteOnclik {
	public static final String SHARE_CONTENT_FOR_INVITE_FRIEND = "拼宝，消费购物打折神器，消费省钱，分享还能赚钱,快来吧%1s";
	public static final String SMS_PRE = "我在拼宝商城想拼购一个商品，一起来拼吧:【%1$s】,点击查看：http://www.178pb.com/home/shopping/%2$s.html";
	public static final String SMS_PRE2 = "是朋友我才告诉你的，我在一元拼宝中奖啦 【%1s】，点击查看：%2s";
	public static final String SHARE_CONTENT = "SHARE_CONTENT";
	private String shareContent;

	private ClearableEditText searchEdt;
	private ListView mLvContact;
	private ContactAdapter contactAdapter;

	private AsyncQueryHandler asyncQuery;
	private String tempCurrentNum;
	private int QUERY_ALL_CONTACTS_TOKEN = 100;
	/** 判断必要的查询, 存放查询系统数据库中的联系人 */
	private Map<String, ContactBean> contactIdMap = new HashMap<String, ContactBean>();
	private List<ContactBean> mList = new ArrayList<ContactBean>();
	private List<ContactBean> Alllist = new ArrayList<ContactBean>();
	private CharacterParser characterParser;
	private ContactSideBar sideBar;
	private TextView dialog, emptyTv;
	private RelativeLayout rlSearch; // 搜索的结果
	private TextView tvSearCh;

	@Override
	protected void initData() {
		super.initData();
		shareContent = getIntent().getStringExtra(SHARE_CONTENT);
	}

	@Override
	public void setRootView() {
		setContentView(R.layout.layout_mobile_contact);
	}

	@Override
	protected void initWidget() {
		super.initWidget();
		new TitleBarHelper(this, -1, R.string.title_select_contacts);
		mLvContact = (ListView) findViewById(R.id.contact_lv);
		searchEdt = (ClearableEditText) findViewById(R.id.search_edit);
		sideBar = (ContactSideBar) findViewById(R.id.sidebar);
		dialog = (TextView) findViewById(R.id.contact_dialog);
		emptyTv = (TextView) findViewById(R.id.contact_tvsearch_empty);
		sideBar.setTextView(dialog);
		characterParser = CharacterParser.getInstance();
		rlSearch = (RelativeLayout) findViewById(R.id.contact_rl_search_empty);
		tvSearCh = (TextView) findViewById(R.id.tv_to_search);
		getPhoneContact();
		initListeners();
	}

	private void getPhoneContact() {
		Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // 联系人的Uri
		String[] projection = { ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.Data.DISPLAY_NAME }; // 查询的列

		asyncQuery = new ContactQueryHandler(getContentResolver());
		asyncQuery.cancelOperation(QUERY_ALL_CONTACTS_TOKEN);
		asyncQuery.startQuery(QUERY_ALL_CONTACTS_TOKEN, null, uri, projection, null, null, "sort_key COLLATE LOCALIZED asc"); // 按照sort_key升序查询
	}

	protected void initListeners() {
		tvSearCh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				closeInput();
				filterData(searchEdt.getText().toString());
			}
		});
		searchEdt.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.toString().length() == 0) {
					contactAdapter.updateListView(Alllist);
					rlSearch.setVisibility(View.GONE);
					sideBar.setVisibility(View.VISIBLE);
				}
			}
		});
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
			@Override
			public void onTouchingLetterChanged(String s) {
				if (!mList.isEmpty() && s != null) {
					// 该字母首次出现的位置
					int position = contactAdapter.getPositionForSection(s.charAt(0));
					if (position != -1) {
						mLvContact.setSelection(position);
					}
				}

			}
		});
	}

	private class ContactQueryHandler extends AsyncQueryHandler {
		@SuppressLint("HandlerLeak")
		public ContactQueryHandler(ContentResolver cr) {
			super(cr);
			showLoadingDialog("");
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
			dismissLoadingDialog();
			if (cursor != null && cursor.getCount() > 0) {
				contactIdMap.clear();
				while (cursor.moveToNext()) {
					String number = cursor.getString(1);
					String tempNum = PhoneUtil.formatIPNumber(number, context);
					String name = cursor.getString(2);
					if (contactIdMap.containsKey(tempNum)) {
						continue;
					}
					else {
						// 总体截取之后不上报服务器；和会员自己的手机号
						if (!VerifyTool.isMobileNO(tempNum) || (!TextUtils.isEmpty(tempCurrentNum) && tempCurrentNum.equals(tempNum))) {
							continue;
						}
						int contactId = cursor.getInt(0);
						ContactBean tempContactBean = new ContactBean();
						tempContactBean.setContactId(contactId);
						tempContactBean.setDisplayName(name);
						tempContactBean.pinyin_dis = characterParser.getSelling(name);
						tempContactBean.setPhoneNum(tempNum);
						contactIdMap.put(tempNum, tempContactBean);
					}
				}
				if (contactIdMap.size() > 0) {
					List<ContactBean> beanList = new ArrayList<ContactBean>();
					for (ConcurrentHashMap.Entry<String, ContactBean> entry : contactIdMap.entrySet()) {
						ContactBean bean = entry.getValue();
						beanList.add(bean);
					}
					mList.addAll(comparedContact(beanList));
					Alllist.addAll(mList);
					contactAdapter = new ContactAdapter(mList, MobileContactActivity.this, MobileContactActivity.this);
					mLvContact.setAdapter(contactAdapter);
				}
				else {
					dismissLoadingDialog();
					showToastMsg("没有联系人");
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setType("vnd.android-dir/mms-sms");
				//	intent.putExtra("sms_body", "拼宝，消费购物打折神器，消费省钱，分享还能赚钱,快来吧" + GlobalApp.getInstance().getUserModel().shareUrl);
					intent.putExtra("sms_body", "选项目、学技术、选址、装修、资金周转、创业交流，想创业来人人创就够了！" + WebNetUtils.getWebUrl("12"));
					// intent.setData(Uri.parse("smsto:" + mContent.getPhoneNum()));// 此为号码
					startActivity(intent);
					finish();
				}
			}
			else {
				dismissLoadingDialog();
				showToastMsg("没有联系人");
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setType("vnd.android-dir/mms-sms");
				//intent.putExtra("sms_body", "拼宝，消费购物打折神器，消费省钱，分享还能赚钱,快来吧" + GlobalApp.getInstance().getUserModel().shareUrl);
				intent.putExtra("sms_body", "选项目、学技术、选址、装修、资金周转、创业交流，想创业来人人创就够了！" + WebNetUtils.getWebUrl("12"));
				// intent.setData(Uri.parse("smsto:" + mContent.getPhoneNum()));// 此为号码
				startActivity(intent);
				finish();
			}
		}
	}

	/**
	 * 比较
	 * 
	 * @description：
	 * @author shicm
	 * @date 2014年7月24日 上午10:49:04
	 */
	private List<ContactBean> comparedContact(List<ContactBean> listWithPhones) {
		List<ContactBean> temp = new ArrayList<ContactBean>();
		for (ContactBean tempStatus : listWithPhones) {
			if (TextUtils.isEmpty(tempStatus.getUserId())) {
				// 有ABCD显示：表示邀请
				String pinyin = characterParser.getSelling(tempStatus.getDisplayName()).substring(0, 1).toUpperCase();
				if (pinyin.matches("[A-Z]")) {
					tempStatus.setSortLetters(pinyin);
				}
				else {
					tempStatus.setSortLetters("#");
				}
				temp.add(tempStatus);
			}
		}
		Collections.sort(temp);
		return temp;
	}

	/**
	 * @description：过滤
	 * @author shicm
	 * @date 2014年12月25日 下午5:50:31
	 */
	private void filterData(String filterStr) {
		if (TextUtils.isEmpty(filterStr)) {
			rlSearch.setVisibility(View.GONE);
			sideBar.setVisibility(View.VISIBLE);
			return;
		}
		List<ContactBean> mSearchBean = new ArrayList<ContactBean>();
		if (TextUtils.isEmpty(filterStr)) {
			rlSearch.setVisibility(View.VISIBLE);
			emptyTv.setText("抱歉,无法找到联系人！");
		}
		else {
			rlSearch.setVisibility(View.GONE);
			sideBar.setVisibility(View.INVISIBLE);
			for (ContactBean temp : mList) {
				String name = temp.getDisplayName();
				String num = temp.getPhoneNum();
				String pName = temp.pinyin_dis;
				if (name.indexOf(filterStr.toString()) != -1 || num.indexOf(filterStr.toString()) != -1 || pName.startsWith(filterStr.toString())) {
					mSearchBean.add(temp);
				}
			}
		}
		if (mSearchBean.size() <= 0) {
			rlSearch.setVisibility(View.VISIBLE);
			emptyTv.setText("抱歉,无法找到联系人！");
			return;
		}
		contactAdapter.updateListView(mSearchBean);
	}

	@Override
	public void tvOnclick(ContactBean mContent) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setType("vnd.android-dir/mms-sms");
		intent.putExtra("sms_body", shareContent);
		intent.setData(Uri.parse("smsto:" + mContent.getPhoneNum()));// 此为号码
		startActivity(intent);
	}
}
